package com.bruip.ssm.controller;

import com.bruip.ssm.pojo.Emp;
import com.bruip.ssm.service.EmpService;
import com.github.pagehelper.PageInfo;
import org.aspectj.weaver.patterns.HasMemberTypePatternForPerThisMatching;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 王若龙
 * @CreateTime 2022-09-08 17:13
 * <p>
 * 1.查询所有的员工信息 /employee get
 * 1.查询分页信息 /employee/page get
 * 2.根据id查询员工信息 /employee/1 get
 * 3.跳转到添加页面 /to/add get
 * 4.添加员工信息 /employee post
 * 5.修改员工信息 /employee put
 * 6.删除员工信息 /employee/1 delete
 */
@Controller
public class EmpController {

    @Autowired
    private EmpService empService;

    @GetMapping("/employee/page/{pageNum}")
    public String getEmployeePage(@PathVariable("pageNum") Integer pageNum, Model model, HttpSession session) {
        PageInfo<Emp> page = empService.getEmployeePage(pageNum);
        model.addAttribute("page", page);
        session.setAttribute("page", page);
        return "employee_list";
    }

    @PostMapping("/employee")
    public String addEmployee(Emp emp, HttpSession session) {
        empService.addEmployee(emp);
        PageInfo<Emp> page = (PageInfo<Emp>) session.getAttribute("page");
        int pages = page.getPages();
        return "redirect:/employee/page/" + pages;
    }

    @GetMapping("/employee")
    public String getAllEmployee(Model model) {
        List<Emp> list = empService.getAllEmployee();
        model.addAttribute("list", list);
        return "employee_list";
    }

    @GetMapping("/employee/{empId}")
    public String toUpdate(@PathVariable("empId") Integer empId, Model model) {
        Emp emp = empService.getEmployeeById(empId);
        model.addAttribute("emp", emp);
        return "employee_update";
    }


    @PutMapping("/employee")
    public String updateEmployee(Emp emp, HttpSession session) {
        empService.updateEmployee(emp);
        PageInfo<Emp> page = (PageInfo<Emp>) session.getAttribute("page");
        int pages = page.getPageNum();
        return "redirect:/employee/page/" + pages;
    }

    @DeleteMapping("/employee/{empId}")
    public String deleteEmployee(@PathVariable("empId") Integer empId, HttpSession session) {
        empService.deleteEmployee(empId);
        PageInfo<Emp> page = (PageInfo<Emp>) session.getAttribute("page");
        int pages = page.getPageNum();
        return "redirect:/employee/page/" + pages;
    }

}
